# coding:utf-8
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import random
import time

import imouse_api

api = imouse_api.HttpApi("127.0.0.1")


def find_image(device_id, file_name, is_click, offset_x, offset_y, total=5):
    """
    在指定设备上查找图片。

    该函数尝试在指定设备上查找指定图片。如果找到图片并且isClick为True，则执行点击操作。
    通过比对预置的阈值来判断图片识别的置信度是否足够高。

    参数:
    - deviceID: 设备ID，标识要在哪个设备上执行查找操作。
    - filename: 图片文件名，要查找的图片。
    - isClick: 是否在找到图片后执行点击操作。
    - offsetX: 点击位置的X坐标偏移量。
    - offsetY: 点击位置的Y坐标偏移量。
    - total: 尝试查找的总次数，默认为5次。

    返回:
    - 如果找到了图片并执行了点击操作，则返回True；否则返回False。
    """
    byte = read_img_by_byte(file_name)

    # 初始化一个标志变量，用于记录是否找到了图片并执行了点击
    tmp = False
    ret = {}
    # 循环尝试查找图片，最多尝试total次
    for i in range(total):
        # 调用API在指定设备上查找图片
        ret = api.find_image(device_id, byte)

        # 如果查找结果状态为0，且数据部分的code为0，且置信度大于等于0.9，则认为找到了图片
        if ret["status"] == 0 and ret["data"]["code"] == 0 and ret["data"]["confidence"] >= 0.9:
            # 如果需要点击图片，则执行点击操作
            if is_click:
                # 计算点击位置的坐标，并执行左键点击，然后移动鼠标到随机位置以模拟自然操作
                api.click(device_id, ret["data"]["result"][0] + offset_x, ret["data"]["result"][1] + offset_y, "left",
                          100)
                time.sleep(0.1)
                api.mouse_move(device_id, random.randint(100, 200), random.randint(100, 500))
            # 设置标志变量为True，表示已找到图片并可能执行了点击
            tmp = True
            # 找到图片后即终止循环
            ret = ret
            break
        else:
            # 如果未找到图片，打印查找结果便于调试
            print("find_image", i, ret, file_name)
        # 每次查找间隔0.4秒
        time.sleep(0.4)
    # 返回是否找到了图片并执行了点击操作
    return {
        "status": tmp,
        "data": ret
    }


def read_img_by_byte(file_name):
    # 使用with语句确保文件资源正确释放
    with open(file_name, "rb") as file:
        img_byte = file.read()
        return img_byte


def findocr(deviceID, ocr, txtLst, isClick):
    for item in ocr["data"]["list"]:
        for txtItem in txtLst:
            if txtItem == item["txt"]:
                if isClick:
                    api.click(deviceID, item["result"][0], item["result"][1], "left")
                return True
    return False


def findocr1(ocr, txt):
    ok = False
    # if ocr["status"] == 0 and ocr["data"]["code"] == 0 and len(ocr["data"]["list"]) > 0:
    for item in ocr["data"]["list"]:
        if item["txt"].find(txt) >= 0:
            ok = True
    return ok


def t2s(t):
    h = 0
    m, s = t.strip().split(":")
    return int(h) * 3600 + int(m) * 60 + int(s)


def hua_shu_str():
    hua_list = []
    hua_list.append(
        'Hi. Are you interested in knowing the agency? I can introduce it to you, and you can get my support after joining.')
    hua_list.append(
        'Hello, I am an authorized agency by TikTok. Follow me, and I can help you smoothly earn more money on TikTok. I can assist you in enhancing your live streaming skills.')
    hua_list.append(
        "Hello, friend. Do you want to have more followers on TikTok and receive more gifts? I am an officially authorized TikTok agency. I can teach you how to livestream better and help you receive more gifts. Follow me.")
    hua_list.append(
        "You're very beautiful. If you want to become popular on TikTok, you can follow me. I can provide you with better livestreaming assistance. I can help you improve. We manage TikTok influencers worldwide and have created many internet celebrities.")
    hua_list.append(
        "Your video recording is very well done, but it lacks likes and views. Follow me. I can assist you. I am from a collaborative agency on TikTok, and we provide free support for managing TikTok creators worldwide. Many excellent creators from the United States, Canada, and Latin America are part of our agency.")
    hua_list.append(
        "I watched your live streaming, it's great, but it lacks some live streaming techniques. Our agency is renowned worldwide. Join us, and I can bring you more assistance. I can teach you more live streaming techniques.")
    hua_list.append(
        "Hello, we are a professional live streaming agency that can help your account gain followers and receive more gifts quickly and for free. Follow me for more assistance; it will allow you to receive greater support and help in building your account.")
    hua_list.append(
        "Hello, if you encounter issues on TikTok, you can follow me. I am an officially authorized TikTok agency, and I can help you communicate with the official platform and try to resolve problems for you.")
    hua_list.append(
        "I've seen all your works, you're amazing! Follow me, and I'll bring you more value, helping you gain more diamonds and followers.")

    # 在这个hua_list里面随机取一个返回
    return random.choice(hua_list)


def find_item_by_txt(data_list, target_txt):
    """
    在数据列表中查找具有指定txt值的项。

    :param data_list: 包含字典的列表，每个字典都有'txt'键。
    :param target_txt: 要查找的txt值。
    :return: 匹配项（字典）或None（如果未找到）。
    """
    for item in data_list:
        if item['txt'] == target_txt:
            return item  # 找到匹配项，返回它
    return None  # 未找到匹配项，返回None


def start_app(device_id):
    find_result = find_image(device_id=device_id, file_name="Screenshot/tiktok.bmp", is_click=True, offset_x=0,
                             offset_y=0)
    if find_result:
        return
    api.send_key(device_id, "", "FN+UpArrow")
    time.sleep(1)

    img_byte = read_img_by_byte("Screenshot/app_ico_0.bmp")

    img_result = api.find_image(deviceid=device_id, img=img_byte, original=True)

    # 检查img_result及其嵌套字典的键是否存在
    if img_result and img_result.get('data', {}).get('code') == 1:
        api.send_key(device_id, "", "FN+UpArrow")
        # 保持方法调用的一致性

        img_result = api.find_image(device_id=device_id, img=img_byte, original=True)

        # 再次检查img_result及其嵌套字典的键是否存在
        if img_result and img_result.get('data', {}).get('result'):
            swipe_x, swipe_y = img_result['data']['result'][:2]
            api.swipe(device_id=device_id, direction="up", sx=swipe_x, sy=swipe_y + 500, ex=swipe_x, ey=swipe_y - 50)
            api.send_key(device_id, "", "FN+UpArrow")

            # 保持方法调用的一致性
            find_result = api.find_image(device_id=device_id, img_path="Screenshot/tiktok.bmp", original=True)
            if not find_result:
                return

            time.sleep(2)


def run(device_id):
    print(device_id)
    start_app(device_id)
    time.sleep(2)
    search_res = api.click(device_id, 348, 68)
    # search_pic = find_image(device_id, "Screenshot/search.bmp", True, 0, 0)

    if not search_res['status'] == 0:
        return
    time.sleep(3)
    # res = api.send_key(deviceID, "Yumi_Enjoyculture")
    user_name = 'yumi_enjoyculture_1'
    res = api.send_key(device_id, user_name)

    ser_cli = find_image(device_id, "Screenshot/search_cli.bmp", True, 0, 0)
    if not ser_cli:
        return
    time.sleep(random.randint(1, 3))

    print("执行到while了")
    while True:
        # 点击搜索按钮
        find = find_image(device_id, "Screenshot/user.bmp", False, 0, 0)
        if find:
            break

    user_ocr_res = api.ocr_ex(device_id, [[3, 140], [3, 249], [371, 140], [371, 249]], True)

    cor_res_list = user_ocr_res['data'].get('list')

    # user_name = 'yumi_enjoyculture_1'

    if cor_res_list and len(cor_res_list) > 0:

        find_res = find_item_by_txt(cor_res_list, user_name)

        if find_res:
            res_cli = api.click(device_id, find_res['result'][0], find_res['result'][1], "left", 100)

        if not res_cli['status'] == 0:
            print("搜索用户结果坐标单击不成功")
            return

    time.sleep(3)
    cli_msg = find_image(device_id, "Screenshot/msg.bmp", True, 0, 0)
    if not cli_msg:
        return

    time.sleep(random.randint(1, 3))

    # 我的x坐标我希望是在 43-300之间的一个随机数
    cli_x = random.randint(50, 260)

    send_msg_cli = api.click(device_id, cli_x, 748, "left", 100)
    if not send_msg_cli['status'] == 0:
        print("发送消息坐标单击不成功")
        return
    send_res = api.send_key(device_id, hua_shu_str())
    if not send_res['status'] == 0:
        print("发送消息不成功")
        return

    # 输入消息后，点击发送
    send_img_cli = find_image(device_id, "Screenshot/send_img.bmp", True, 0, 0)
    if not send_img_cli:
        return
    time.sleep(random.randint(1, 3))

    # 返回用户页面
    back_cli = find_image(device_id, "Screenshot/back.bmp", True, 0, 0)
    if not back_cli:
        return

    follow_cli = find_image(device_id, "Screenshot/follow.bmp", True, 0, 0)
    if not follow_cli:
        return
    time.sleep(random.randint(1, 3))


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # deviceidLst = []
    # deviceidLst.append('6C:E8:5C:A0:E7:52')  # 群控多台手机1
    # # deviceidLst.append('DC:2B:2A:14:2A:F6')   #群控多台手机2
    # # deviceidLst.append('DC:2B:2A:14:2A:F2')   #群控多台手机3
    # # deviceidLst.append('DC:2B:2A:14:2A:F3')   #群控多台手机4
    # for deviceId in deviceidLst:
    #     thread1 = threading.Thread(target=run, args=(deviceId,))
    #     thread1.start()
    #     time.sleep(1)

    deviceId = "6C:E8:5C:A0:E7:52"

    run(deviceId)

    # while True:
    #     cmd = input("请输入:")
    #     if cmd == "q":
    #         break
